package com.ruoyi.framework.web.service;

import com.ruoyi.common.core.domain.entity.CustomUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.user.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @Classname CustomUserDetailServiceImpl
 * @Description
 * @Date 2025/11/10 15:49
 * @Created by 小哲
 */
@Component
public class CustomUserDetailServiceImpl implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        CustomUser customUser = userMapper.selectUserByPhone(username);
        if (Objects.isNull(customUser)) {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException("登录用户：" + username + " 不存在");
        }
        return createLoginUser(customUser);
    }
    public UserDetails createLoginUser(CustomUser customUser) {
        return new LoginUser(customUser.getId(), customUser);
    }

}
